var currentClassUnit;

var classhourscb = new Ext.grid.CheckboxSelectionModel();

    var data=[['启用','1'],['禁用','2']];
	var groupStore = new Ext.data.SimpleStore({
             fields: ['statusName', 'status'],
             data : data
        });
    var iscsjgdata=[['是','1'],['否','2']];
	var iscsjgStore = new Ext.data.SimpleStore({
             fields: ['statusName', 'agenciesType'],
             data : iscsjgdata
        });


	// 新增科室表单
	var classHoursForm = new Ext.FormPanel({
		labelSeparator : ':',  
		frame : true,   
		labelAlign : 'right',  
		border:false,
		items : [{
					name : "unitId",
					fieldLabel : "单位编号",
					xtype : "hidden"
				},{
					name : "unitCode",
					fieldLabel : "单位代码",
					xtype : "textfield",
					readOnly : true
				}, {
					name : "code",
					fieldLabel : "科室代码",
					xtype : "textfield",
					allowBlank : false,
					blankText : "科室代码不能为空!"
				}, {
					name : "name",
					fieldLabel : "科室名称",
					xtype : "textfield",
					allowBlank : false,
					blankText : "科室名称不能为空!"
				},{
					name : "shortname",
					fieldLabel : "简称",
					xtype : "textfield"
				},{
					name : "type",
					fieldLabel : "类型",
					xtype : "textfield"
				},{
					hiddenName : 'status',
					valueField : 'status',
					fieldLabel : "状态",
					xtype : "combo",
					width : 140,
					store:groupStore, 
					displayField : 'statusName',
					forceSelection: false,
					mode: 'local',
					emptyText:'请选择'
				},{
					name : "order",
					fieldLabel : "次序",
					xtype : "textfield"
				},{
					hiddenName : 'agenciesType',
					valueField : 'agenciesType',
					fieldLabel : "是否是常设机构",
					xtype : "combo",
					width : 140,
					store:iscsjgStore, 
					displayField : 'statusName',
					forceSelection: false,
					mode: 'local',
					emptyText:'请选择'
				}],
		buttonAlign : "center",
		buttons : [{
					text : "保存",
					handler : function() {
						if (classHoursForm.getForm().isValid()) {
							classHoursForm.getForm().submit({
										url : '/classHours.action?method=add',
										waitMsg : '正在保存数据...',
										success : onAddClassSuccess,
										failure : onAddClassFailure
									});
						}
					}

				}, {
					text : "关闭",
					handler : function(){
						classHoursFormWin.hide();
					}
				}]
	});
	
	// 修改表单
	var editclassHoursForm = new Ext.FormPanel({
		labelSeparator : ':',  
		frame : true,   
		border:false,
		items : [{
					name : "id",
					fieldLabel : "编号",
					xtype : "hidden"
				},{
					name : "unitId",
					fieldLabel : "单位编号",
					xtype : "hidden"
				},{
					name : "unitCode",
					fieldLabel : "单位代码",
					xtype : "textfield",
					readOnly : true
				}, {
					name : "code",
					fieldLabel : "科室代码",
					xtype : "textfield",
					allowBlank : false,
					blankText : "科室代码不能为空!"
				}, {
					name : "name",
					fieldLabel : "科室名称",
					xtype : "textfield",
					allowBlank : false,
					blankText : "科室名称不能为空!"
				},{
					name : "shortname",
					fieldLabel : "简称",
					xtype : "textfield"
				},{
					name : "type",
					fieldLabel : "类型",
					xtype : "textfield"
				},{
					hiddenName : 'status',
					valueField : 'status',
					fieldLabel : "状态",
					xtype : "combo",
					width : 140,
					store:groupStore, 
					displayField : 'statusName',
					forceSelection: false,
					mode: 'local',
					emptyText:'请选择'
				},{
					name : "order",
					fieldLabel : "次序",
					xtype : "textfield"
				},{
					hiddenName : 'agenciesType',
					valueField : 'agenciesType',
					fieldLabel : "是否是常设机构",
					xtype : "combo",
					width : 140,
					store:iscsjgStore, 
					displayField : 'statusName',
					forceSelection: false,
					mode: 'local',
					emptyText:'请选择'
				}],
		buttonAlign : "center",
		buttons : [{
					text : "保存",
					handler : function() {
						if (editclassHoursForm.getForm().isValid()) {
							editclassHoursForm.getForm().submit({
										url : '/classHours.action?method=update',
										waitMsg : '正在保存数据...',
										success : onAddClassSuccess,
										failure : onAddClassFailure
									});
						}
					}

				}, {
					text : "关闭",
					handler : function(){
						editclassHoursFormWin.hide();
					}
				}]
	});
	
	function onAddClassFailure(form, action) {
		if (action.failureType == "connect") {
			Ext.Msg.alert('服务器异常', '服务器异常，请与管理员联系！');
		} else {
			Ext.Msg.alert('错误', '您输入的用户名和密码错误！');
		}
	};
	
	function onAddClassSuccess(form, action) {
		classHoursFormWin.hide();
		editclassHoursFormWin.hide();
    	classhoursds.reload();
		Ext.MessageBox.alert("提示", action.result.message); 
	};

	//添加
    function addSysUnits(){
    	if(currentUnit != null){
    		var unitId = currentUnit.attributes.id;
    		var unitCode = currentUnit.attributes.code;
	    	classHoursForm.form.reset();
	    	classHoursForm.getForm().findField('unitId').setValue(unitId); //赋值单位编号
	    	classHoursForm.getForm().findField('unitCode').setValue(unitCode);
			classHoursForm.isAdd = true;
			classHoursFormWin.setTitle("新增科室");
			classHoursFormWin.show();
    	}else{
    		Ext.Msg.alert('提示','请选择单位！');
    	}
    };
    
    //修改
    function editSysUnits(){
    	var unitsList = classhoursGrid.getSelectionModel().getSelections();
    	var idList = [];
    	if(unitsList.length == 0){
    		Ext.MessageBox.alert('提示','请选择要操作的科室!')
    	}else if(unitsList.length>1){
    		Ext.MessageBox.alert('提示','只能为一个科室修改!')
    	}else{
    		for(var i=0; i<unitsList.length; i++){
    			idList.push(unitsList[i].get('id'));
    		}
	    	editclassHoursForm.form.reset();
			editclassHoursForm.isAdd = true;
			editclassHoursFormWin.setTitle("修改参数类型");
			editclassHoursFormWin.show();
			var id = idList[0];
    		editloadUnitsForm(id);
    	}
    };
    
     //删除
    function deleteSysUnits(){
    	var unitsList = classhoursGrid.getSelectionModel().getSelections();
    	var idList = [];
    	if(unitsList.length == 0){
    		Ext.MessageBox.alert('提示','请选择要操作的科室!')
    	}else{
    		for(var i=0; i<unitsList.length; i++){
    			idList.push(unitsList[i].get('id'));
    		}
    		Ext.MessageBox.confirm('提示','您确定要删除选定的参数类型吗?',
    		function(btnId){
    			if(btnId == 'yes'){
    				deleteClassHoursAjax(idList);
    			}
    		});
    	}
    } 
    
    function deleteClassHoursAjax(propertyId){
    	  var msgTip = Ext.MessageBox.show({
           msg: '正在删除所选项目, 稍后...',
           progressText: '删除...',
           width:300,
           wait:true,
           waitConfig: {interval:200}
       });
    	
    	Ext.Ajax.request({
    		url : '/classHours.action?method=delete',
    		params : {ids:propertyId},
    		method : 'POST',
    		success : function(response, options){
    			msgTip.hide();
    			var result = Ext.util.JSON.decode(response.responseText);
    			if(result.success){
    				for(var i=0; i < propertyId.length; i++){
	    				var index = classhoursds.find('id',propertyId[i]);
		    			if(index != -1){
		    				var rec = classhoursds.getAt(index);
		    				classhoursds.remove(rec);
		    			}
	    			}
    				Ext.Msg.alert('提示','成功删除项目');
    			}else{
    				Ext.Msg.alert('提示','该参数类别不能删除，因为含有子项.');
    			}
    		},
    		failure : function(response, options){
    			msgTip.hide();
    			Ext.Msg.alert('提示','删除失败.');
    		}
    	});
    }
    
    // 加载数据到Form表单(修改)
	function editloadUnitsForm(propertyId) {
		editclassHoursForm.form.load({
					waitMsg : '正在加载数据',
					waitTitle : '提示',
					url : '/classHours.action?method=findByCode',
					params : {
						id : propertyId
					},
					method : 'GET',
					success : function(form, action) {
						// 数据加载成功.
					},
					failure : function(form, action) {
						Ext.Msg.alert('无法加载该数据');
					}
				});
	}
    
    //添加unit弹出的窗口.
	var classHoursFormWin = new Ext.Window({
		layout:'fit',
		width:380,
		height:400,
		closeAction:'hide',
		resizable:false, 
		shadow : true, 
		modal:true, 
		closable:true,
		bodyStyle:'padding:5 5 5 5',
		animCollapse:true, 
		items:[classHoursForm]
	});
	
	 //修改unit弹出的窗口.
	var editclassHoursFormWin = new Ext.Window({
		layout:'fit',
		width:380,
		height:400,
		closeAction:'hide',
		resizable:false, 
		shadow : true, 
		modal:true, 
		closable:true,
		bodyStyle:'padding:5 5 5 5',
		animCollapse:true, 
		items:[editclassHoursForm]
	});


	//定义数据存储器
	var classhoursds = new Ext.data.Store({  
		proxy:new Ext.data.HttpProxy({ 
			url:"/classHours.action?method=page",
			method:"post"
		}),
		reader:new Ext.data.JsonReader({
			root:"data",
			totalProperty:'totalProperty'
		},[  
			{name : 'id'},
			{name : 'unitId'},
			{name : 'unitCode'},
			{name : 'code'},
			{name : 'name'}
		])
	}) ;
	
	//定义列类型
	var classHourscolumn = new Ext.grid.ColumnModel([
		classhourscb,
		new Ext.grid.RowNumberer({header:'行号',width:40}),
		{header: '编号', dataIndex: 'id', width: 180},
		{header: '单位编号', dataIndex: 'unitId', width: 100},
		{header: '单位代码', dataIndex: 'unitCode', width: 100},
        {header: '科室名称', dataIndex: 'name', width: 100},
        {header: '科室代码', dataIndex: 'code', width: 100}
    ]);
    classHourscolumn.defaultSortable = true;
    
    var text_search_chName = new Ext.form.TextField({
		name : 'textSearchchName',
		width : 100,
		emptyText : '请输入科室名称!'
		
	});
	var text_search_chCode = new Ext.form.TextField({
		name : 'textSearchchCode',
		width : 100,
		emptyText : '请输入科室代码!'
		
	});
	var searchClassHours = function() {
		var searchName = text_search_chName.getValue();
		var searchCode = text_search_chCode.getValue();
		classhoursds.load({params : {start : 0,limit : 9 , searchCode : searchCode,searchName : searchName}});
	}
	var btn_search_classHours = new Ext.Button({
		text : '查询',
		icon:'icons/toolBar/search.gif',
		handler : searchClassHours
	});
    
    var classHourstoolbar = new Ext.Toolbar([
    	{text:'新增科室',icon:'icons/toolBar/add.gif',handler : addSysUnits},'-',
    	{text:'修改科室',icon:'icons/toolBar/plugin.gif',handler : editSysUnits},'-',
    	{text:'删除科室',icon:'icons/toolBar/delete.gif',handler : deleteSysUnits},'-'
    	//'-',text_search_chName,'-',text_search_chCode,btn_search_classHours
    ]);
     
    //创建表格
    classhoursGrid = new Ext.grid.GridPanel({
    	id : 'classTab',
    	title : '单位科室',
    	//el : 'classhours-grid-div',
    	//width:Ext.get("content").getWidth(),
    	height:Ext.get("content").getHeight(),
    	viewConfig:{forceFit:true},
    	store : classhoursds,
    	cm : classHourscolumn,
    	trackMouseOver : false,
    	loadMask : {
					msg : '正在加载数据，请稍侯……'
				},
    	sm : classhourscb,
    	tbar : classHourstoolbar,
    	bbar: new Ext.PagingToolbar({
	            pageSize: 10,      
	            store: classhoursds,
	            displayInfo: true,
	            displayMsg: '显示第 {0} 条到 {1} 条记录，一共 {2} 条',
	            emptyMsg: "没有记录"
	        }),
	    listeners: {activate: classHandleActivate}
    });
    
    function classHandleActivate(){
    	if(currentUnit != null && currentClassUnit != currentUnit){
    		var unitId = currentUnit.attributes.id;
			if(unitId != null && unitId != ''){
				currentClassUnit = currentUnit;
	    		classhoursds.load({params:{start:0,limit:10,propertyId:unitId}});
			}
    	}
    }
